/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package generatecsr;

/**
 *
 * @author rmartinezch
 */

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;

import javax.security.auth.x500.X500Principal;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;

public class GenerateCSR {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws NoSuchAlgorithmException, OperatorCreationException, IOException {
        // TODO code application logic here
        //loading the BC provider and setting it as a default provider
        Provider bc = new BouncyCastleProvider();
        Security.insertProviderAt(bc, 1);
        
        KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
        gen.initialize(2048);
        KeyPair pair = gen.generateKeyPair();
        
        PrivateKey privateKey = pair.getPrivate();
        PublicKey publicKey = pair.getPublic();
        
        System.out.println("---");
        System.out.println(privateKey);
        System.out.println("---");
        
        //http://www.bouncycastle.org/wiki/display/JA1/BC+Version+2+APIs
        ContentSigner signGen = new JcaContentSignerBuilder("SHA1withRSA").build(privateKey);
        
        X500Principal subject = new X500Principal("C=NO, ST=Trondheim, L=Trondheim, O=Senthadev, OU=Innovation, CN=www.senthadev.com, EMAILADDRESS=senthadev@gmail.com");
        PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(subject, publicKey);
        PKCS10CertificationRequest request = builder.build(signGen);
        
        OutputStreamWriter output = new OutputStreamWriter(System.out);
        PEMWriter pem = new PEMWriter(output);
        pem.writeObject(request);
        pem.close();
    }
    
}
